import axios from 'axios'

const BASE = 'http://localhost:8000/enterprise/'

export async function uploadAvatar(file, type = 'avatar') {
  const form = new FormData()
  form.append('image_file', file)
  form.append('type', type)
  const res = await axios.post(`${BASE}avatar_uploadview/`, form, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
  return res.data
}

export async function submitPersonalInfo({ name, avatar, position, token }) {
  const res = await axios.post(
    `${BASE}personal/`,
    { name, avatar, position },
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

export async function submitCompanyInfo({ personal, company, token }) {
  const res = await axios.post(
    `${BASE}company/`,
    { personal, company },
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

export async function fetchMainInfo(token) {
  const res = await axios.get(`${BASE}main/`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return res.data
}

// 获取公司详情（无需登录）
export async function fetchCompanyDetail(companyId) {
  const res = await axios.get(`${BASE}company/${companyId}/`)
  return res.data
}

// 发布职位
export async function createJob(payload, token) {
  const res = await axios.post(
    `${BASE}jobs/`,
    payload,
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

// 更新职位
export async function updateJob(jobId, payload, token) {
  const res = await axios.put(
    `${BASE}jobs/${jobId}/`,
    payload,
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

// 切换职位状态（PATCH方法）
export async function toggleJobStatus(jobId, token) {
  const res = await axios.patch(
    `${BASE}jobs/${jobId}/`,
    {},
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

// 删除职位
export async function deleteJob(jobId, token) {
  const res = await axios.delete(
    `${BASE}jobs/${jobId}/`,
    { headers: { Authorization: `Bearer ${token}` } }
  )
  return res.data
}

// 数据统计API
const STATS_BASE = 'http://localhost:8000/data/'

/**
 * 查询统计数据
 * @param {Object} params - 查询参数
 * @param {number} params.period - 统计周期（1=日，2=周，3=月）
 * @param {string} params.stats_date - 统计日期（格式YYYY-MM-DD）
 * @param {number} params.stats_type - 统计类型（1=业务指标，2=合规指标，3=互动指标，0=全部）
 * @param {string} token - 认证token
 */
export async function fetchStatsData({ period, stats_date, stats_type = 0 }, token) {
  const res = await axios.get(`${STATS_BASE}stats/`, {
    params: {
      period,
      stats_date,
      stats_type
    },
    headers: { Authorization: `Bearer ${token}` }
  })
  return res.data
}